package cn.stylefeng.guns.modular.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.modular.entity.ScheduleForm;
import cn.stylefeng.guns.modular.entity.ScheduleFormItem;
import cn.stylefeng.guns.modular.entity.ScheduleFrame;
import cn.stylefeng.guns.modular.service.ScheduleDraftService;
import cn.stylefeng.guns.modular.service.ScheduleFormItemService;
import cn.stylefeng.guns.modular.service.ScheduleFormService;
import cn.stylefeng.guns.modular.service.ScheduleFrameService;
import cn.stylefeng.guns.modular.utils.MailOperation;
import cn.stylefeng.roses.core.base.controller.BaseController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping(value = "/mySchedule")
public class MyScheduleController extends BaseController {

    @Autowired
    private ScheduleFormService scheduleFormService ;
    @Autowired
    private ScheduleFrameService scheduleFrameService;
    @Autowired
    private ScheduleDraftService scheduleDraftService;
    @Autowired
    private ScheduleFormItemService scheduleFormItemService;



    /**
     * 加载我的首页
     * @return
     */
    @RequestMapping(value ="myFirst" )
    public String loadMyFirst(){
        return "/myfirst.html";
    }

    /**
     * 显示我的首页
     * @return
     */
    @RequestMapping(value ="myFirst" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> showMyFirst(Model model){
        /**
         * 得到当前登陆者的信息
         */
        LoginUser user = LoginContextHolder.getContext().getUser();
        long userId= user.getId();
        //查询该用户的两个日程框架
        List<ScheduleFrame> scheduleFrames =scheduleFrameService.showScheduleFrameLimitTwo(userId);
        System.out.println("============scheduleFrames=========="+scheduleFrames);
        //查询该用户的最近两个日程表
        List<ScheduleForm> scheduleForms=  scheduleFormService.showLimitTwo(userId);
        //草稿栏默认显示最新的三个日程框架
        List<ScheduleFrame> scheduleDraftFrame =scheduleDraftService.showScheduleDraftLimitThree(userId);
        //查看该用户今日所有行程
       Date date= new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String dateStr=sdf.format(date);
        System.out.println("=================="+dateStr);
       List<ScheduleFormItem> scheduleFormItems=scheduleFormItemService.showTodaySfromItem(userId,dateStr);
        System.out.println("========1234================"+scheduleFormItems);
        Map<String,Object> map =new HashMap();
        map.put("scheduleForms",scheduleForms);
        map.put("scheduleFrames",scheduleFrames);
        map.put("scheduleDraftFrame",scheduleDraftFrame);
        map.put("scheduleFormItems",scheduleFormItems);

        JSONObject result = JSONObject.parseObject(JSON.toJSONString(map));
        System.out.println("+++++++++"+result);
        model.addAttribute("result",result);
        return result;
    }







    @RequestMapping(value = "/test")
    public String scheduleForm(Model model ,ScheduleFrame scheduleFrame,ScheduleForm scheduleFormSave) {
        /**
         * 得到当前登陆者的信息
         */
        LoginUser user = LoginContextHolder.getContext().getUser();
        long userId= user.getId();
        //
       List<ScheduleForm> scheduleForm = scheduleFormService.selectAllScheduleForm(userId);
       //
     List<ScheduleFrame> scheduleFrames =scheduleFrameService.selectAllScheduleFrame(userId);
        scheduleFrame.setSframeName("框架123");
       ScheduleFrame scheduleFrame1ByName =  scheduleFrameService.selectScheduleFrameByName("框架123",userId);
        System.out.println(scheduleFrame1ByName);
       if (scheduleFrame1ByName==null){
           scheduleFrameService.saveScheduleFrame(scheduleFrame);
       }else {
           System.out.println("框架名字不能重复");
       }

       //插入日程表

       //模仿选择的框架id是1;
        scheduleFormSave.setSframeId(1);
       scheduleFormSave.setSformName("日程表四");
        System.out.println(scheduleForm+"==========================================================");
       ScheduleForm scheduleFormByname=  scheduleFormService.selectScheduleFormByAllName("日程表四",userId);
        System.out.println(scheduleForm+"==========================================================");
        if (scheduleFormByname==null){
            ////保存日程表
            scheduleFormService.saveScheduleForm(scheduleFormSave);
        }else {
            System.out.println("日程表不能重复");
        }


        //根据框架id查询
        ScheduleFrame scheduleFrame1 =scheduleFrameService.selectScheduleFrameById(1);
   /*  //根据id查询日程表
       long userId =(long) 1 ;
     ScheduleForm scheduleFormById =  scheduleFormService.selectById(1);*/
        for (ScheduleForm scheduleForm1: scheduleForm
             ) {
            System.out.println(scheduleForm1);
        }

      /*  List<ScheduleForm> listForm=scheduleFormService.fuzzySearchSForm("日程",userId);*/
        List<ScheduleForm> listForm=null;
        //  查看所有已共享的日程表
        //已共享的情况下
        List<ScheduleFrame> scheduleFrameIsShare= scheduleFrameService.selectAllScheduleFramePublish();
        System.out.println("============================================"+scheduleFrameIsShare);

        //模拟选择的sformId为4
        int sformid=4;
       int rows = scheduleFormService.deletScheduleFormBy(sformid);
       if (rows==1){
           System.out.println("删除成功！");
       }else {
           System.out.println("删除失败！");
       }

       //模拟选择日程框架3
       int sframeid=3;
       int isDelete =scheduleFrameService.deleteScheduleFrameById(sframeid);
       if (isDelete==1){
           System.out.println("删除成功！");
       }else{
           System.out.println("删除失败！");
       }




        model.addAttribute("scheduleFrames",scheduleFrames);
//        model.addAttribute("scheduleFormById",scheduleFormById);
        model.addAttribute("scheduleForm",scheduleForm);
        model.addAttribute("scheduleFrame1",scheduleFrame1);
        model.addAttribute("scheduleFrameIsShare",scheduleFrameIsShare);


        return "/testForm.html";
    }



    @RequestMapping(value = "/asa")
    public String sendEmail() {

        return "/myfirst.html";
    }




    @RequestMapping(value = "/asa" ,method = RequestMethod.POST )
    public String sendEmail1(String email) {
        System.out.println(email);
        MailOperation operation = new MailOperation();
        String user = "welson_lin@163.com";//你的邮箱地址
        String password = "1314lsw";//你的邮箱授权码
        String host = "smtp.163.com";//设置邮件服务器主机名
        String from = "welson_lin@163.com"; //你的邮箱地址
//        String to = "1076507930@qq.com";// 收件人

        String subject = "code"; //输入邮件主题
        //邮箱内容
        StringBuffer sb = new StringBuffer();
        System.out.println((int)((Math.random()*9+1)*100000));

        String yzm =""+ (int)((Math.random()*9+1)*100000);
        sb.append("<!DOCTYPE>"+"<div bgcolor='#f1fcfa'   style='border:1px solid #d9f4ee; font-size:14px; line-height:22px; color:#005aa0;padding-left:1px;padding-top:5px;   padding-bottom:5px;'><span style='font-weight:bold;'>温馨提示：</span>"
                + "<div style='width:950px;font-family:arial;'>欢迎注册日程共享管理系统！您已成为我们中的一员，您的注册码为：<br/><h2 style='color:green'>"+yzm+"</h2><br/>本邮件由系统自动发出，请勿回复。<br/>感谢您的使用。<br/>广东石油化工学院</div>"
                +"</div>");
        try {
            String res = operation.sendMail(user, password, host, from, email,
                    subject, sb.toString());
            System.out.println(res);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return "/myschedule.html";
    }







    @RequestMapping(value ="test_htmls" )
    public String testHtmls(){

        return "/sharedCommunity.html";
    }

    @RequestMapping("/fuwenben")
    public String fuwenben(){
        return "/fuwenben.html";

    }

    @RequestMapping(value ="/saveFuWenBen")
    @ResponseBody
    public String saveFuWenBen(String data){
        System.out.println("=================="+data);




        return "/fuwenben.html";

    }
}
